#!/usr/bin/env bash

pull_toolchain() {
  local oldpwd=$(pwd)
  local newpwd=$(dirname $1)
  local staging=$(basename $1)
  cd $newpwd
  if [ ! -d "$staging" ]; then
    git clone http://gitlab.local/toolchain/${staging}.git
  else
    cd $staging
    git pull origin master
  fi
  cd $oldpwd
}

build() {
  rm -f ./${buildName}-$buildPlatform
  local goEnvOpts="GOARCH=$buildPlatform"
  local striper=strip
  case $buildPlatform in
  1619b)
    staging=$(readlink -f ~/toolchain-1619b)
    pull_toolchain $staging
    cc=$staging/bin/aarch64-tnas-linux-gnu-gcc
    cxx=$staging/bin/aarch64-tnas-linux-gnu-g++
    striper=$staging/bin/aarch64-tnas-linux-gnu-strip
    goEnvOpts="GOARCH=arm64 GOARM=7 CC=$cc CXX=$cxx STAGING_DIR=$staging/aarch64-tnas-linux-gnu/sysroot/"
    ;;
  amd64)
    #staging=$(readlink -f ~/toolchain-amd64)
    #pull_toolchain $staging
    #cc=$staging/bin/x86_64-tnas-linux-gnu-gcc
    #cxx=$staging/bin/x86_64-tnas-linux-gnu-g++
    #striper=$staging/bin/x86_64-tnas-linux-gnu-strip
    #goEnvOpts="GOARCH=amd64 CC=$cc CXX=$cxx STAGING_DIR=$staging/x86_64-tnas-linux-gnu/sysroot"
    goEnvOpts="GOARCH=amd64"
    ;;
  1619b-new)
    staging=$(readlink -f ~/toolchain-1619b-new)
    pull_toolchain $staging
    cc=$staging/bin/aarch64-openwrt-linux-gnu-gcc
    cxx=$staging/bin/aarch64-openwrt-linux-gnu-g++
    striper=$staging/bin/aarch64-openwrt-linux-gnu-strip
    export CGO_FLAGS="--sysroot=$staging/sysroot"
    export CGO_LDFLAGS="--sysroot=$staging/sysroot"
    goEnvOpts="GOARCH=arm64 GOARM=7 CC=$cc CXX=$cxx STAGING_DIR=$staging/sysroot/"
    ;;
  esac
  env CGO_ENABLED=1 GOOS=linux $goEnvOpts go build -tags="nomsgpack sonic avx" -ldflags "-s -w" -o ./output/${buildName}-$buildPlatform
  $striper ./output/${buildName}-$buildPlatform

  if [ "$buildName" == "thumbnailTool" ] || [ "$buildName" == "tersql" ] || [ "$buildName" == "iniparse" ]; then
    cp -a ./output/${buildName}-$buildPlatform ./${buildName}-$buildPlatform
    echo ./${buildName}-$buildPlatform
  else
    upx --best --lzma -9 -f -o ./${buildName}-$buildPlatform ./output/${buildName}-$buildPlatform # upx压
    #  upx --ultra-brute -o ./${buildName}-$buildPlatform ./output/${buildName}-$buildPlatform #极限压缩，速度极慢
  fi

  if [ $buildFlag -ne 1 -a -d "$startPWD/files" ]; then
    local destDir="$startPWD/files${outputDir}"
    [ ! -d "$destDir" ] && mkdir -p "$destDir"
    cp ./${buildName}-$buildPlatform "${destDir}/${buildName}" -a
    if [ ! -z "$linkName" ]; then
      ln -s ${buildName} $linkName
      cp $linkName "${destDir}/${linkName}" -a
      rm -f $linkName
    fi
    rm -f ./${buildName}-$buildPlatform
  fi
}

clean() {
  if [ $buildFlag -ne 1 ]; then
    local destDir="$startPWD/files${outputDir}"
    rm -f "${destDir}/${buildName}" 2>/dev/null
  fi
}
